﻿using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace BToolkit
{
    public class Drag2D : MonoBehaviour
    {
        public bool xEnable = true;
        public bool yEnable = true;

        public Action onBeginDrag, onEndDrag;
        internal bool isDraging;
        Vector2 _previousPos;

        protected virtual void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
                if (hit.collider != null && hit.collider.gameObject == gameObject)
                {
                    OnTouchDown();
                }
            }

            if (isDraging)
            {
                Vector2 currPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                Vector2 delta = currPos - _previousPos;
                _previousPos = currPos;
                Vector3 pos = transform.position;
                if (xEnable)
                {
                    pos.x += delta.x;
                }
                if (yEnable)
                {
                    pos.y += delta.y;
                }
                transform.position = pos;
            }

            if (Input.GetMouseButtonUp(0))
            {
                if (isDraging)
                {
                    isDraging = false;
                    onEndDrag?.Invoke();
                }
            }
        }

        private void OnTouchDown()
        {
            _previousPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            isDraging = true;
            onBeginDrag?.Invoke();
        }

    }
}